package com.neardrug.controller;

import cn.hutool.json.JSONUtil;
import com.neardrug.common.Constants;
import com.neardrug.common.Result;
import com.neardrug.context.BaseContext;
import com.neardrug.exception.ServiceException;
import com.neardrug.system.AsyncTaskFactory;
import com.neardrug.vo.MarkdownVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;

@RestController
@Api(tags = "专利页面")
@RequestMapping("/patents")
public class PatentsController {
    // 创建一个不验证SSL证书的HttpClient
    private static CloseableHttpClient createHttpClient() throws IOException {
        try {
            // 创建一个不验证SSL证书的SSLContext
            SSLContext sslContext = SSLContextBuilder.create()
                    .loadTrustMaterial((chain, authType) -> true) // 允许所有证书
                    .build();

            return HttpClients.custom()
                    .setSSLContext(sslContext)
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) // 不验证主机名
                    .build();
        } catch (Exception e) {
            throw new IOException("Failed to create HttpClient with SSL context", e);
        }
    }

    @PostMapping
    @ApiOperation("生成专利")
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()){
            throw new ServiceException(Constants.PARAM_ERROR,"文件为空");
        }
        String wordFile="";
        try(CloseableHttpClient client = createHttpClient()) {
            String url="https://lilab.ecust.edu.cn/markushpatent/claims_generate";
            // 使用 MultipartEntityBuilder 构建请求体
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            HttpPost post = new HttpPost(url);
            builder.addBinaryBody(
                    "file", // 参数名
                    file.getInputStream(), // 文件输入流
                    ContentType.APPLICATION_OCTET_STREAM, // 文件内容类型
                    file.getOriginalFilename() // 文件名
            );
            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode==200) {//如果请求响应正确
                // 读取响应体
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuilder responseBody = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    responseBody.append(line);
                }

                // 获取原始JSON字符串
                String result = responseBody.toString();
                // 解析 JSON 响应体
                JSONObject jsonResponse = new JSONObject(responseBody.toString());
                String data=jsonResponse.optString("data","");
                if (data.equals("")){
                    throw new ServiceException(Constants.CODE_500,"无返回数据");
                }
                JSONObject dataJsonObject = new JSONObject(data);
                wordFile = dataJsonObject.optString("word_file", "");
                if (wordFile.equals("")){
                    throw new ServiceException(Constants.CODE_500,"无返回数据");
                }
            }
        } catch (Exception e) {
            throw new ServiceException(Constants.FILE_ERROR,"文件分析发生错误");
        }
        return Result.success(wordFile);
    }
}
